package com.bestv.search.management.datasyn;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.*;

public class ProgramSync extends QuartzJobBean {

    final static String cfgFile = "progSync.properties";
    static boolean isRunning = false;
    Logger logger = Logger.getLogger(ProgramSync.class);

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        if (!isRunning) {
            isRunning = true;
            run();
        } else {
            logger.error("Last sync process is still running");
        }
    }

    void run() {
        logger.info("Start program sync @" + new Date());
        PropertiesConfiguration config;
        try {
            config = new PropertiesConfiguration(cfgFile);
        } catch (ConfigurationException e) {
            logger.error("Load config property failed");
            logger.error(e.toString());
            e.printStackTrace();
            return;
        }
        config.setReloadingStrategy(new FileChangedReloadingStrategy());
        List<?> branches = config.getList("branch.list");
        Map<String, String> p;
        for (int i = 0; i < branches.size(); i++) {
            String branch = ((String) branches.get(i)).toLowerCase();
            Iterator<?> it = config.getList(branch + ".program.syncers").iterator();
            while (it.hasNext()) {
                String syncer = (String) it.next();
                if (!config.containsKey(branch + ".program.s." + syncer + ".status")
                        || config.getInt(branch + ".program.s." + syncer + ".status") != 1)
                    continue;
                p = new HashMap<String, String>(0);
                p.put("cfgFile", cfgFile);
                p.put("branch", branch);
                p.put("syncer", syncer);
                Iterator<?> it2 = config.getKeys();
                while (it2.hasNext()) {
                    String key = (String) it2.next();
                    if (key.startsWith(branch + ".program.s." + syncer)) {
                        p.put(key.substring((15 + syncer.length())), config.getString(key));
                    }
                }
                try {
                    ProgramSyncManager.sync(p);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    logger.error("Sync error! branch@" + branch + ", syncer@" + syncer);
                }
            }
        }
        logger.info("End program sync @" + new Date());
        isRunning = false;
    }
}
